
import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect } from 'react';
import { View, Text, Switch, Button, Input } from '@tarojs/components';

import { sendPhoneCode} from '../../api/auth';
import PageHeader from '../../components/pageHeader';
import DataErrorView from '../../components/dataError';
import { useAppContext } from '../../contexts/AppContext';
import DataLoadingView from '../../components/dataLoading';
import { UserAvatarImage } from '../../components/userAvatar';
import { removeToken, uploadUserFile } from '../../contexts/store';
import { 
  getUserInfo, changePassword, changePhone, deleteAccount, 
  updateUserInfoApi, updateUserSettingApi, getUserSettingApi, 
  sendFeedbackApi 
} from '../../api/user';

import './index.scss';


/**
 * 用户设置页面
 * 用于用户管理个人设置和偏好
 */
const UserSettingsPage: React.FC = () => {
  const { userInfo, setUserInfo } = useAppContext();
  const [settings, setSettings] = useState({
    notifications: true,
    pushMessages: true,
  });
  const userId = Number(userInfo?.id);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [userPhone, setUserPhone] = useState<string>('');
  const [code, setCode] = useState<string>('');
  const [feedback, setFeedback] = useState<string>('');
  const [isSendingCode, setIsSendingCode] = useState<boolean>(false);
  const [countdown, setCountdown] = useState<number>(0);
  const [oldPassword, setOldPassword] = useState<string>('');
  const [newPassword, setNewPassword] = useState<string>('');
  const [forgotPassword, setForgotPassword] = useState<boolean>(false);
  const [username, setUsername] = useState<string>(userInfo?.username || '');

  const fetchUserInfo = async () => {
    try {
      setLoading(true);
      await getUserInfo().then((userInfoResponse) => {
        if (userInfoResponse.code === 200 && userInfoResponse.data) {
          setUserInfo({ ...userInfoResponse.data, updateTime: new Date().getTime() });
        }else {
          Taro.showToast({
            icon: 'error',
            title: '获取用户信息失败',
          })
        }
      });
      await getUserSettingApi().then((userSettingResponse) => {
        if (userSettingResponse.code === 200 && userSettingResponse.data) {
          setSettings({
            notifications: userSettingResponse.data.notifications,
            pushMessages: userSettingResponse.data.pushMessages,
          });
        }
      })
    } catch (error) {
      console.error('获取用户信息失败:', error);
      Taro.showToast({
        icon: 'error',
        title: '获取用户信息失败',
      })
    } finally {
      setLoading(false);
    }
  };

  const handleSendCode = async () => {
    if (!/^1[0-9]\d{9}$/.test(userPhone)) {
      if (Taro && typeof Taro.showToast === 'function') {
        Taro.showToast({
          title: '请输入有效的手机号',
          icon: 'none'
        });
      }
      return;
    }
    if (isSendingCode) {
      return;
    }

    try {
      setIsSendingCode(true);
      const success = await sendPhoneCode(userPhone);
      if (success) {
        if (Taro && typeof Taro.showToast === 'function') {
          Taro.showToast({
            title: '验证码发送成功',
            icon: 'success'
          });
        }
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(timer);
              setIsSendingCode(false);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        Taro.showToast({
          title: '发送验证码失败，请重试',
          icon: 'none'
        });
        setIsSendingCode(false);
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      Taro.showToast({
        title: '发送验证码失败，请重试',
        icon: 'none'
      });
      setIsSendingCode(false);
    }
  };

  useEffect(() => {
    fetchUserInfo();
  }, []);

  const handleSettingToggle = (settingKey: keyof typeof settings, value: boolean) => {
    setSettings(prev => ({
      ...prev,
      [settingKey]: value
    }));
    updateUserSetting(settingKey, value);
  };

  const handleSaveUserInfo = async (userName: string ='', userAvatar: string ='') => {
    if(!userInfo?.id) {
      return;
    }
    try {
      await updateUserInfoApi({
        id: Number(userInfo?.id),
        value: userName || userAvatar,
        type:  userName?'username':'avatar',
      }).then((res) => {
        if (res.code === 200) {
          console.log(882, res.data)
          setUserInfo(res.data);
          Taro.showToast({
            title: '更新成功',
            icon: 'success'
          });
        }
      })
    } catch (err) {
      console.error('Failed to save user info:', err);
    }
  };

  const handleUserAvatar = async(e: any) => {
    const { avatarUrl } = e.detail;
    try {
      let fileType = avatarUrl.split(".").pop() || 'png';
      const res: any = await uploadUserFile(avatarUrl, 'avatar.'+fileType, 'image/png', 'user_avatar.'+fileType, userId);
      if (res.code == 200) {
        const fileName = res.data.file_name;
        handleSaveUserInfo('', fileName)
      }else{
        Taro.showToast({
          icon: 'none',
          title: '头像上传失败，请重试',
        })
      }
    } catch (error) {
      Taro.showToast({
        icon: 'none',
        title: '头像上传失败，请重试',
      })
    }
  }

  const handleUpdatePhone = async() => {
    await changePhone(userPhone, code).then((res) => {
      if (res.code === 200) {
        Taro.showToast({
          title: '更新成功',
          icon: 'success'
        });
      }
    }).catch((err) => {
      Taro.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  }

  /**
   * 处理修改密码
   */
  const handleChangePassword = async() => {
    await changePassword(oldPassword, newPassword, '', '').then((res) => {
      if (res.code === 200) {
        Taro.showToast({
          title: '更新成功',
          icon: 'success'
        });
      }
    }).catch((err) => {
      Taro.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  };

  /**
   * 处理遗忘密码
   */
  const handleForgotPassword = async() => {
    await changePassword('', newPassword, userPhone, code).then((res) => {
      if (res.code === 200) {
        Taro.showToast({
          title: '更新成功',
          icon: 'success'
        });
      }
      setForgotPassword(false);
    }).catch((err) => {
      Taro.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  };

  const deleteUserAccount = async() => {
    Taro.showModal({
      title: '确认注销账户',
      content: '确认注销账户后，该账户所有信息将被清除',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确认',
      success: (res) => {
        if (res.confirm) {
          deleteAccount().then((res) => {
            if (res.code === 200) {
              removeToken(setUserInfo);
              Taro.showToast({
                title: '注销成功',
                icon: 'success'
              });
              Taro.navigateTo({ url: '/pages/login/index' });
            }
          });
          Taro.navigateTo({ url: '/pages/login/index' });
        }
      }
    });
  }

  const handleFeedbackSubmit = async() => {
    if(!feedback) {
      Taro.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      })
      return;
    }
    await sendFeedbackApi(feedback).then(res => {
      if(res.code == 200) {
        setFeedback("")
        Taro.showToast({
          title: '反馈成功',
          icon: 'success'
        })
      }
    }).catch(err => {
      Taro.showToast({
        title: err.message,
        icon: 'none'
      })
    });
  }

  const updateUserSetting = async(Key, value) => {
    await updateUserSettingApi(
      Key==='notifications'?value:settings.notifications,
      Key==='pushMessages'?value:settings.pushMessages,
    ).then((res) => {
      if (res.code !== 200) {
        Taro.showToast({
          title: '更新失败',
          icon: 'error'
        });
      }
    })
  }

  if (!userInfo || userInfo.role === 0) {
    return (
      <DataErrorView title="获取用户信息失败" buttonText='重新登录' onClickFunc={() => Taro.navigateTo({ url: '/pages/login/index' })}/>
    );
  }

  return (
    <View className="page-container">
      <PageHeader title="设置" />
      <View className="content">
        {loading ? (
          <DataLoadingView />
        ) : error ? (
          <DataErrorView title="获取用户信息失败" buttonText='重新登录' onClickFunc={() => Taro.navigateTo({ url: '/pages/login/index' })}/>
        ) : (
          <>
            {/* 用户信息设置 */}
            <View className="settings-section">
              <Text className="settings-section-title text-sm">个人信息</Text>
              <View className="settings-user-info-card">
                {/* 头像上传区域 */}
                <View className="settings-info-section">
                  <Text className='settings-info-label text-base'>头像：</Text>
                  <View className='settings-avatar-section'>
                    <UserAvatarImage
                      isTourist={userInfo.role === 0}
                      avatar={userInfo.avatar}
                      user_id={Number(userInfo.id) || 0}
                      user_name={userInfo.username || '游客'}
                    />
                  </View>
                  <Button openType="chooseAvatar" className='settings-update-avatar-btn' onChooseAvatar={handleUserAvatar}>更新</Button>
                </View>

                <View className='settings-info-section'>
                    <Text className='settings-info-label text-base'>昵称：</Text>
                    <Input type='text' maxlength={10} className="settings-user-name text-lg" focus value={username} onInput={v => setUsername(v.detail.value)} />
                    {username && username!= userInfo.username && <Button className='settings-update-avatar-btn' onClick={() => handleSaveUserInfo(username)}>更新</Button>}
                </View>
                {!forgotPassword && (<View className='settings-info-section'>
                    <Text className='settings-info-label text-base'>原密码：</Text>
                    <Input type='text' placeholder='' maxlength={11} className="settings-user-name text-lg"  value={oldPassword} onInput={v => setOldPassword(v.detail.value)} />
                    {!forgotPassword && <Button className='settings-update-avatar-btn' onClick={() => setForgotPassword(true)}>忘记密码</Button>}
                </View>)}
                <View className='settings-info-section'>
                    <Text className='settings-info-label text-base'>新密码：</Text>
                    <Input type='text' placeholder='' maxlength={11} className="settings-user-name text-lg"  value={newPassword} onInput={v => setNewPassword(v.detail.value)} />
                    {!forgotPassword && newPassword && <Button className='settings-update-avatar-btn' onClick={() => handleChangePassword()}>更新</Button>}
                    {forgotPassword && <Button className='settings-cancel-btn' onClick={() => setForgotPassword(false)}>取消</Button>}
                </View>
                <View className='settings-info-section'>
                    <Text className='settings-info-label text-base'>手机号：</Text>
                    <Input type='text' placeholder='' maxlength={11} className="settings-user-name text-lg"  value={userPhone} onInput={v => setUserPhone(v.detail.value)} />
                </View>
                {((!forgotPassword && userPhone && userPhone.length > 0) || forgotPassword) && (
                  <View className='settings-info-section'>
                      <Text className='settings-info-label text-base'>验证码：</Text>
                      <Input type='number' placeholder='' maxlength={6} className="settings-user-name text-lg" value={code} onInput={v => setCode(v.detail.value)} />
                      {userPhone && userPhone.length == 11 && (
                        <Button
                          className='settings-update-avatar-btn'
                          onClick={handleSendCode}
                        >
                          {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                        </Button>
                      )}
                  </View>
                )}
                {!forgotPassword && userPhone && userPhone.length == 11 && code && (
                  <View className='settings-info-section'>
                    <Button className='settings-update-phone-btn' onClick={handleUpdatePhone}>更新手机号</Button>
                  </View>
                )}
                {forgotPassword && (
                  <View className='settings-info-section'>
                    <Button className='settings-update-phone-btn' onClick={handleForgotPassword}>更新密码</Button>
                  </View>
                )}
              </View>
            </View>

            {/* 通知设置 */}
            <View className="settings-section">
              <Text className="section-title">通知设置</Text>
              
              <View className="settings-list">
                <View className="settings-user-info-card">
                  <View className="setting-item">
                    <Text className="setting-label text-md">接收客服消息通知</Text>
                    <Switch 
                      className='setting-switch'
                      checked={settings.notifications} 
                      onChange={(e) => handleSettingToggle('notifications', e.detail.value)}
                    />
                  </View>
                  <View className="setting-item">
                    <Text className="setting-label text-md">接收教练消息推送</Text>
                    <Switch 
                      className='setting-switch'
                      checked={settings.pushMessages} 
                      onChange={(e) => handleSettingToggle('pushMessages', e.detail.value)}
                    />
                  </View>
                </View>
              </View>
            </View>

            {/* 投诉与建议 */}
            <View className="settings-section">
              <Text className="section-title">投诉建议</Text>
              <View className="settings-list">
                <View className="settings-user-info-card">
                  <View style={{ width: '100%' }}>
                    <Input maxlength={200} className='settings-textarea text-base' value={feedback} onInput={v => setFeedback(v.detail.value)} />
                  </View>
                  <View className="setting-submit-btn">
                    <Button type="primary" size='default' plain onClick={handleFeedbackSubmit}>提交</Button>
                  </View>
                </View>
              </View>
            </View>
            
            {/* 删除账户 */}
            <View className="settings-section">
              <Text className="section-title">账户操作</Text>
              <View className="settings-list">
                <View className="settings-user-info-card">
                  <View>
                    <View className="orange-tag text-md">
                      <MaterialIcons name="warning" size={24} color="#FF4D4F" style={{ marginRight: 10 }}/>
                      删除账户后，您将无法再使用该账号登录；
                    </View>
                    <View className="orange-tag text-md"> 您的所有数据将被删除，将无法享受平台优惠活动~</View>
                  </View>
                  <View className="setting-submit-btn text-sm">
                    <Button type="warn" size='default' plain onClick={deleteUserAccount}>注销账户</Button>
                  </View>
                </View>
              </View>
            </View>
          </>
        )}
      </View>
    </View>
  );
};

export default UserSettingsPage;